package com.smallA.service.Impl;

import com.smallA.constant.DataConstant;
import com.smallA.constant.RequestConstant;
import com.smallA.mapper.ExamMapper;
import com.smallA.mapper.ExamQuestionMapper;
import com.smallA.mapper.GradeMapper;
import com.smallA.po.*;
import com.smallA.service.ExamService;
import com.smallA.utils.DataUtils;
import com.smallA.utils.TypeConverterUtils;
import com.smallA.vo.Result;
import com.smallA.vo.ResultExam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.*;

@Service("ExamService")
public class ExamServiceImpl implements ExamService {

    @Resource
    private ExamMapper examMapper;
    @Resource
    private DataUtils dataUtils;
    @Resource
    private ExamQuestionMapper examQuestionMapper;
    @Resource
    private GradeMapper gradeMapper;


    @Deprecated
    private List randomList(List list, int count) {
        Random ra = new Random();
        List<Object> result = new ArrayList<>();
        if (count < 0) {
            return result;
        }
        for (int i = 0; i < count; i++) {
            result.add(list.remove(ra.nextInt(list.size())));
        }
        return result;
    }

    /**
     * 通过试卷id来查询对应的试卷问题并封装进map
     *
     * @param eid 试卷id
     * @return 返回查询到的试卷问题集合
     */
    @Deprecated
    private Map<String, Object> getQuestionMapByExamId(int eid) {
        if (dataUtils.examineNumber(eid)) {
            return null;
        }
        List<Choice> choices = examMapper.selectChoiceByExamId(eid);
        List<Fill> fills = examMapper.selectFillByExamId(eid);
        List<ShortAnswer> shortAnswers = examMapper.selectShortAnswerByExamId(eid);
        Map<String, Object> map = new HashMap<>();
        map.put(DataConstant.QUESTION_CHOICE, choices);
        map.put(DataConstant.QUESTION_FILL, fills);
        map.put(DataConstant.QUESTION_SHORT_ANSWER, shortAnswers);
        return map;
    }


    @Override
    public Result<Exam> selectExamById(Integer gid) {
        if (dataUtils.examineNumber(gid)) {
            return new Result<>(400, RequestConstant.HTTP_400);
        }
        return new Result<>(examMapper.selectExamAndAnswerByGid(gid));
    }

    @Override
    public Exam selectExamByExamId(Integer eid) {
        if (dataUtils.examineNumber(eid)) {
            return null;
        }
        return examMapper.selectExamById(eid);
    }

    @Override
    public ResultExam selectExamByGradeId(Integer gid) {
        if (dataUtils.examineNumber(gid)) {
            return null;
        }
        Grade grade = gradeMapper.selectGradeById(gid);
        return TypeConverterUtils.converterResultExam(selectExamByExamId(grade.getTest().getExamId()), grade.getTest().getContext());
    }


    @Override
    @Deprecated
    public Exam autoExam(Integer[] topicTypeIds, Integer choiceCount, Integer fillCount, Integer shortAnswerCount, String context, Integer tid, Integer score) {
        if (dataUtils.examineNumArray(topicTypeIds) || dataUtils.examineNumber(tid, score) || dataUtils.examineStr(context, 100)) {
            return null;
            //没有类型题还出个鬼子,直接不做了
        }
        if (choiceCount <= 0 && fillCount <= 0 && shortAnswerCount <= 0) {
            System.out.println("2");
            // 如果要出的所有内容都是空的还出个鬼子
            return null;
        }
        //先通过对应的id查询对应的类型题
        List<Choice> choices = null;
        if (choiceCount > 0) {
            choices = examMapper.selectChoiceByTypeIds(topicTypeIds);
        }
        if (choices != null && choices.size() < choiceCount) {
            //如果最后查询出来的数据小于要求就肯定是传入的数据有问题,直接null返回
            return null;
        }
        List<Fill> fills = null;
        if (fillCount > 0) {
            fills = examMapper.selectFillByTypeIds(topicTypeIds);
        }
        if (fills != null && fills.size() < fillCount) {
            return null;
        }
        List<ShortAnswer> shortAnswers = null;
        if (shortAnswerCount > 0) {
            shortAnswers = examMapper.selectShortAnswerByTypeIds(topicTypeIds);
        }
        if (shortAnswers != null && shortAnswers.size() < shortAnswerCount) {
            return null;
        }
        //查询完成就可以开始操作了,随机添加数据到数组
        List<Choice> c = randomList(choices, choiceCount);
        List<Fill> f = randomList(fills, fillCount);
        List<ShortAnswer> sa = randomList(shortAnswers, shortAnswerCount);
        float difficult = 0;
        for (Choice choice : c) {
            difficult += choice.getDifficulty();
        }
        for (Fill fill : f) {
            difficult += fill.getDifficulty();
        }
        for (ShortAnswer shortAnswer : sa) {
            difficult += shortAnswer.getDifficulty();
        }
        difficult = difficult / (choiceCount + fillCount + shortAnswerCount);
        //创建一个试卷数据并查询出来对应的id
        if (examMapper.insertExam(tid, context, difficult, score) < 0) {
            return null;
        }
        Exam exam = examMapper.selectExam(tid, context, score);
        if (exam == null) {
            return null;
        }
        //现在,试卷有了,题目有了,开始操作
        int id = exam.getId();
        float sc = score / (choiceCount + fillCount + shortAnswerCount);
        for (Choice choice : c) {
            examMapper.addQuestionInExam(id, choice.getId(), 1, sc);
        }
        for (Fill fill : f) {
            examMapper.addQuestionInExam(id, fill.getId(), 2, sc);
        }
        for (ShortAnswer shortAnswer : sa) {
            examMapper.addQuestionInExam(id, shortAnswer.getId(), 3, sc);
        }
        //上传完毕,查询数据后返回即可
        return selectExamByExamId(id);
    }

    @Override
    public List<Exam> selectAllExam() {
        List<Exam> exams = examMapper.selectAllExam();
        return exams;
    }

    @Override
    public Exam autoAdd(Integer[] topicTypeIds, Integer choiceCount, Integer fillCount, Integer shortCount, String analyze, int score, int tid) {
        //判
        if (dataUtils.examineNumber(choiceCount,fillCount,shortCount,score,tid)||dataUtils.examineStr(analyze,100)) {
            return null;
        }

        if(dataUtils.examineNumArray(topicTypeIds)){
            return null;
        }
        List<Choice> choices = new ArrayList<>();
        List<Fill> fills = new ArrayList<>();
        List<ShortAnswer> shortAnswers = new ArrayList<>();
        //通过topic查询题目类型，再到选择，填空，简答题表查询具体题型，返回三个集合
        if (choiceCount > 0) {
            choices = examMapper.selectChoiceByTypeIds(topicTypeIds);
            if (choices != null && choices.size() < choiceCount) {
                return null;
            }
        }

        if (fillCount > 0) {
            fills = examMapper.selectFillByTypeIds(topicTypeIds);
            if (fills != null && fills.size() < fillCount) {
                return null;
            }
        }

        if (shortCount > 0) {
            shortAnswers = examMapper.selectShortAnswerByTypeIds(topicTypeIds);
            if (shortAnswers != null && shortAnswers.size() < shortCount) {
                return null;
            }
        }
        //每种类型遍历count个数，每次随机获取集合里的一个对象
        List<Choice> choiceList = randomList(choices, choiceCount);
        List<Fill> fillList = randomList(fills, fillCount);
        List<ShortAnswer> shortAnswerList = randomList(shortAnswers, shortCount);
        //计算难度插入exam表，返回一个exam_id
        float difficulty = 0;
        for (Choice choice : choiceList) {
            difficulty+=choice.getDifficulty();
        }
        for (Fill fill : fillList) {
            difficulty+=fill.getDifficulty();
        }
        for (ShortAnswer shortAnswer : shortAnswerList) {
            difficulty+=shortAnswer.getDifficulty();
        }
        DecimalFormat df = new DecimalFormat("#.00");
        difficulty = Float.parseFloat(df.format(difficulty/(choiceCount+fillCount+shortCount)));
        if(examMapper.insertExam(tid, analyze, difficulty, score)<0){
            return null;
        }
        Exam exam = examMapper.selectExam(tid, analyze, score);
        Float singleScore = Float.parseFloat(df.format(score/(choiceCount+fillCount+shortCount)));
        //通过exam_id将随机题目插入到exam和question的中间关联表
        for (Choice choice : choiceList) {
            examQuestionMapper.addQuestionInExam(exam.getId(),choice.getId(),1,singleScore);
        }
        for (Fill fill : fillList) {
            examQuestionMapper.addQuestionInExam(exam.getId(),fill.getId(),2,singleScore);
        }
        for (ShortAnswer shortAnswer : shortAnswerList) {
            examQuestionMapper.addQuestionInExam(exam.getId(),shortAnswer.getId(),3,singleScore);
        }
        //最终返回一个exam对象
        return selectExamByExamId(exam.getId());
    }
}
